package com.kaochong.xcx.utils;

import com.kaochong.xcx.cache.WordCache;
import com.kaochong.xcx.pojo.cache.OptionModel;
import com.kaochong.xcx.pojo.cache.WordModel;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;

/**
 * @author han
 * @date 2018-06-08 18:29
 */
@Slf4j
@Component
public class MixUtil {
	
	@Autowired
	WordCache wordCache;
	
	/**
	 * 混淆答案
	 * @param wordList
	 * @param type 四六级
	 * @return
	 */
	public Map<String, Object> mixUp(List<WordModel> wordList, Integer type){
		// 1、打乱题库顺序
		Collections.shuffle(wordList);
		
		Map<String, Object> result = madeRandomOption(wordList, type);
		return result;
	}
	
	/**
	 * 根据已有问题 制造混淆答案的问题
	 * @param wordList
	 * @return
	 */
	private Map<String, Object> madeRandomOption(List<WordModel> wordList, Integer type) {
		// 3、生成ids集合
		List<Integer> ids = new ArrayList<>(wordList.size());
		
		int randomCount = 0;
		for (int i = 0; i < wordList.size(); i++) {
			int index = i + 1;
			WordModel word = wordList.get(i);
			// ids集合
			ids.add(word.getId());
			
			// 真实答案
			int realAnswerIndex = RandomUtils.nextInt(4) + 1;
			word.setIndex(index);
			word.setRealAnswer(realAnswerIndex);
			
			// 4、加入混淆答案
			List<OptionModel> optionModelList = new ArrayList<>();
			// 按词性查找单词
			List<OptionModel> sexWord = wordCache.getSexWord(word.getEnSex(), type);
			
			Set<Integer> optionIdSet = new HashSet<>();
			Set<String> optionZhSet = new HashSet<>();
			optionIdSet.add(word.getId());
			optionZhSet.add(word.getZh());
			// 将正确答案和错误答案混淆在一起
			for (int j = 1; j <= 4; j++) {
				OptionModel option = new OptionModel();
				option.setIndex(j);
				if (realAnswerIndex == j) {
					option.setId(word.getId());
					option.setZh(word.getZh());
				} else {
					Integer optionIndex;
					Integer id;
					String zh;
					do {
						optionIndex = RandomUtils.nextInt(sexWord.size());
						randomCount++;
						id = sexWord.get(optionIndex).getId();
						zh = sexWord.get(optionIndex).getZh();
					} while (optionIdSet.contains(id) || optionZhSet.contains(zh));
					optionIdSet.add(id);
					optionZhSet.add(zh);
					
					option.setIndex(j);
					option.setId(sexWord.get(optionIndex).getId());
					option.setZh(sexWord.get(optionIndex).getZh());
				}
				optionModelList.add(option);
			}
			
			word.setOptions(optionModelList);
		}
		log.info("随机了{}次", randomCount);
		Map<String, Object> result = new HashMap<>();
		result.put("ids", ids);
		result.put("wordList", wordList);
		return result;
	}
}
